import type { ActionType, FormInstance, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { Button, Form, message, Modal, Tag } from 'antd';
import { memo, useEffect, useRef, useState } from 'react';
import { delete_embedding, llm_embedding } from '../../api/request';
import CustomSelect from '../../components/CustomSelect';
import Examine from './components/Examine';
import KnowledgeEdit from './components/KnowledgeEdit';
import { useLocation } from 'react-router-dom';
import { LlmEmbedding } from '../../api/http.d';
export const waitTimePromise = async (time: number = 100) => {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve(true);
        }, time);
    });
};

export const waitTime = async (time: number = 100) => {
    await waitTimePromise(time);
};

const KnowledgeDocumnet = () => {
    const actionRef = useRef<ActionType>();
    const [isExamine, setIsExamine] = useState(false);
    const [markdown, setMarkdown] = useState('');
    const [isKnowledgeEdit, setIsKnowledgeEdit] = useState(false);
    const [markdownId, setMarkdownId] = useState(0);
    const [knowledgeType, setKnowledgeType] = useState<'create' | 'update'>('create');
    const [documentId, setDocumentId] = useState<number>();
    const { state } = useLocation();
    const formRef = useRef<FormInstance>();

    const columns: ProColumns<LlmEmbedding>[] = [
        {
            dataIndex: 'index',
            valueType: 'indexBorder',
            width: 48,
        },
        {
            title: '文档',
            dataIndex: 'projectName',
            width: 180,
            search: false,
            ellipsis: true,
        },
        {
            title: '文档',
            dataIndex: 'documentIds',
            ellipsis: true,
            width: 180,
            hidden: true,
            renderFormItem: () => {
                return <CustomSelect mode="multiple" />
            }
        },
        {
            disable: true,
            title: '文本',
            fieldProps: {
                placeholder: '向量检索'
            },
            dataIndex: 'document',
            ellipsis: {
                showTitle: false,
            }
        },
        {
            disable: true,
            title: '字数',
            width: 80,
            search: false,
            render: (dom, entity) => {
                return <Tag color="red">{entity.document.length}</Tag>;
            }
        },
        {
            disable: true,
            title: '相似度',
            dataIndex: 'distance',
            width: 80,
            search: false,
            render: (dom, entity) => {
                return <Tag color="blue">{entity.distance.toFixed(3)}</Tag>;
            }
        },
        {
            title: '操作',
            valueType: 'option',
            key: 'option',
            width: 230,
            render: (text, record, _, action) => [
                <Button type="link" style={{ padding: 0 }}
                    onClick={() => {
                        setDocumentId(record.documentId)
                        setMarkdown(record.document)
                        setMarkdownId(record.id)
                        setIsKnowledgeEdit(true)
                        setKnowledgeType('update')
                    }}>
                    编辑
                </Button>,
                <Button type="link" style={{ padding: 0 }}
                    onClick={() => {
                        setMarkdown(record.document)
                        setIsExamine(true)
                    }}>
                    查看
                </Button>,
                <Button type="link" style={{ padding: 0 }}
                    onClick={() => {
                        Modal.confirm({
                            title: '删除',
                            content: '是否删除',
                            onOk: async () => {
                                await delete_embedding(record.id)
                                Modal.destroyAll();
                                setMarkdownId(record.id)
                                message.success("删除成功")
                                actionRef.current?.reload();
                            }
                        })
                    }}>
                    删除
                </Button>
            ],
        },
    ];

    useEffect(() => {
        if (state?.id) {
            formRef.current.setFieldValue('documentIds', [state?.id])
            formRef.current?.submit();
            actionRef.current?.reload();
        }
    }, [])

    return (
        <>
            <ProTable<LlmEmbedding>
                columns={columns}
                formRef={formRef}
                actionRef={actionRef}
                request={async (params) => {
                    params.documentIds = params.documentIds.join(',')
                    return await llm_embedding(params);
                }}
                rowKey="id"
                search={{
                    labelWidth: 'auto',
                }}
                options={{
                    setting: {
                        listsHeight: 400,
                    },
                }}
                pagination={{
                    pageSize: 5
                }}
                headerTitle="向量数据库"
            />

            {/* Markdown编辑 */}
            <KnowledgeEdit
                markdown={markdown}
                type={knowledgeType}
                open={isKnowledgeEdit}
                onChange={(open) => setIsKnowledgeEdit(open)}
                id={markdownId}
                documentId={documentId}
                onOk={(open) => {
                    actionRef.current?.reload()
                    setIsKnowledgeEdit(open)
                }} />

            {/* Markdown查看 */}
            <Examine
                markdown={markdown}
                open={isExamine}
                onChange={(open) => setIsExamine(open)} />
        </>
    );
};

export default memo(KnowledgeDocumnet)